<template>
    <el-dialog
        :fullscreen="fullscreen"
        v-model="dialogVisible"
        :title="title"
        width="700"
        :before-close="handleClose"
    >
        <fc-designer v-if="dialogVisible" :config="{ fieldReadonly: false }" v-show="fullscreen" ref="designer" :style="{height: contentHeight}"/>
        <div v-show="!fullscreen">
            <el-form
                v-loading="loading"
                ref="ruleFormRef"
                :model="dataForm"
                :rules="rules"
                label-width="auto"
            >
                <el-form-item label="访问权限" prop="accessMode">
                    <el-segmented v-model="dataForm.accessMode" :options="locationOptions" />
                </el-form-item>
                <el-form-item :label="accessModeConfig.label" prop="accessMode" v-if="accessModeConfig.isShow">
                    <user-list v-model="dataForm.accessList" />
                </el-form-item>
                <el-form-item label="版本号" prop="version">
                    <el-input v-model="dataForm.version" placeholder="请输入" />
                </el-form-item>
                <el-form-item label="描述" prop="description">
                    <el-input v-model="dataForm.description" :rows="2" type="textarea" placeholder="请输入" />
                </el-form-item>
                <el-form-item label="脚本" prop="file">
                    <div style="display: flex; align-items: flex-start;">
                        <el-upload
                            v-if="dialogVisible"
                            class="upload-demo"
                            :auto-upload="false"
                            :limit="1"
                            action=""
                            :on-change="handleFileChange"
                        >
                            <el-button type="primary">选择脚本</el-button>
                        </el-upload>
                        <el-button @click="handleSetConfig" type="success" style="margin-bottom: 10px; margin-left: 10px;">配置表单</el-button>
                    </div>
                </el-form-item>
            </el-form>
        </div>
        <template #footer>
            <div class="dialog-footer" v-if="!fullscreen">
                <el-button @click="setDialogVisible(false)" :disabled="loading">取消</el-button>
                <el-button type="primary" @click="submit" :disabled="loading">确定</el-button>
            </div>
            <div v-else>
                <el-button type="primary" @click="saveFormConfig()">确定</el-button>
            </div>
        </template>
    </el-dialog>
</template>
<script setup>
import { importFormApi, getUischemaApi, updateInfoApi } from "@/api/scriptManage/index.api";
import useToggle from "@/hooks/useToggle";
const [loading, , setLoading] = useToggle();
const [dialogVisible, , setDialogVisible] = useToggle();
const [fullscreen, , setFullscreen] = useToggle();

import UserList from '@/components/UserList/index.vue'

const emit = defineEmits(['refresh'])
const rowId = ref(null)

const title = computed(() => {
    let label = '导入脚本'
    if(rowId.value) label = '编辑'
    if(fullscreen.value) label = '配置表单'
    return label
})

const enumAccessModes = {
    public: '公开',
    whitelist: '白名单',
    blacklist: '黑名单',
}

const locationOptions = computed(() => {
    return Object.keys(enumAccessModes).map(key => ({
        label: enumAccessModes[key],
        value: key,
    }))
})

const accessModeConfig = computed(() => {
    const isShow = ['whitelist', 'blacklist'].includes(dataForm.value.accessMode)
    const label = enumAccessModes[dataForm.value.accessMode]
    return { label, isShow }
})

const dataForm = ref({
    accessMode: 'public',
    accessList: [],
    version: '',
    description: '',
    file: null,
})

const rules = computed(() => ({
    file: [{ required: title.value === '编辑' ? false : true, message: '请选择脚本', trigger: 'change' }],
}))

const handleFileChange = (file) => {
    dataForm.value.file = file.raw
}

const handleSetConfig = () => {
    setFullscreen(true)
}

const submit = async () => {
    await ruleFormRef.value.validate((valid, fields) => {
        if (!valid) return
        const body = {
            uischema: uischema.value,
            accessMode: dataForm.value.accessMode,
            accessList: dataForm.value.accessMode === 'public' ? [] : dataForm.value.accessList,
            version: dataForm.value.version,
            description: dataForm.value.description,
        }
        const fileData = new FormData()
        if(dataForm.value.file) fileData.append('file', dataForm.value.file)
        fileData.append('metadata', JSON.stringify(body))

        if(rowId.value) return editRow(fileData, rowId.value)
        addRow(fileData)
    })
}

const editRow = (fileData, id) => {
    setLoading(true)
    updateInfoApi(fileData, id).then(res => {
        if(res){
            ElMessage.success('编辑成功')
            emit('refresh')
        }
    }).finally(() => {
        setLoading(false)
        setDialogVisible(false)
    })
}

const addRow = (fileData) => {
    setLoading(true)
    importFormApi(fileData).then(res => {
        if(res){
            ElMessage.success('导入成功')
            emit('refresh')
        }
    }).finally(() => {
        setLoading(false)
        setDialogVisible(false)
    })
}

const uischema = ref([])
const designer = ref(null)
const saveFormConfig = () => {
    const json = designer.value.getJson()
    uischema.value = JSON.parse(json)
    setFullscreen(false)
}

const handleClose = () => {
    setDialogVisible(false)
}

const ruleFormRef = ref(null)
const init = (row) => {
    setFullscreen(false)
    setDialogVisible(true);
    nextTick(() => {
        uischema.value = []
        ruleFormRef.value.resetFields()

        if (row) {
            rowId.value = row.id
            dataForm.value = {
                accessMode: row.accessMode,
                accessList: row.accessList,
                version: row.version,
                description: row.description,
                file: null,
            }
            getFormConfig()
        } else {
            rowId.value = null
        }
    })
}

const getFormConfig = () => {
    console.log(designer.value)
    getUischemaApi(rowId.value).then(res => {
        if(Array.isArray(res)){
            uischema.value = res
            designer.value.setRule(uischema.value)
        }
    })
}

const contentHeight = computed(() => {
    return `${window.innerHeight - 120}px`
})

defineExpose({
    init,
})
</script>
